<template>
  <d2-container>
    <div class="row-ac pb-2">
      <div><el-button type="warning" @click="addCategory" icon="el-icon-plus">添加分类</el-button></div>
      <div class="ml-2"><el-button type="danger" icon="el-icon-delete">批量删除</el-button></div>
    </div>
    <div class="d-f">
      <div class="category-tree">
        <div class="category-tree-title row text-white">产品分类列表</div>
        <div class="flex-1 mt-2">
          <el-tree :data="categoriesTree" :props="defaultProps" accordion @node-click="handleNodeClick">
          </el-tree>
        </div>
      </div>
      <div class="flex-1 ml-2">
        <el-table :data="categoriesList" stripe>
          <el-table-column align="center" type="selection" width="55" />
          <el-table-column align="center" label="序号" type="index" width="65" />
          <el-table-column align="center" label="分类名称" prop="category_name" width="130" />
          <el-table-column align="center" label="封面广告" prop="image" width="150">
            <template slot-scope="scope">
              <el-popover placement="right" trigger="hover">
                <el-image slot="reference" style="width: 40px; height: 40px" :src="scope.row.cover_image" fit="cover" />
                <el-image style="width: 220px; height: 220px" :src="scope.row.cover_image" fit="contain" />
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column align="center" label="icon图标" prop="icon" width="65" />
          <el-table-column align="center" label="上级分类" prop="parent_name" width="65" />
          <el-table-column align="center" label="排序" prop="sort" width="45" />
          <el-table-column align="center" label="操作" width="180">
            <template slot-scope="scope">
              <el-button size="mini" @click="categorEdit(scope.row.id)">修改</el-button>
              <el-button size="mini" type="danger" @click="openDelete(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="flex-1 mt-3">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page.sync="queryInfo.page" layout="total, prev, pager, next" :total="total">
          </el-pagination>
        </div>
        <el-dialog :visible.sync="dialogVisible" width="40%" title="添加/编辑分类">
          <el-form :model="form" :rules="rules" ref="form" label-width="80px">
            <el-form-item label="名称" prop="category_name">
              <div style="width: 50%;">
                <el-input v-model="form.category_name"></el-input>
              </div>
            </el-form-item>
            <el-form-item label="父分类" prop="parent">
              <div style="width: 50%;">
                <el-cascader v-model="form.parent" :props="{value:'id', label: 'category_name', checkStrictly: true}"
                  :options="categoriesTree" @change="handleChange"></el-cascader>
              </div>
            </el-form-item>
            <el-form-item label="分类图标" prop="adver_image">
              <el-upload class="avatar-uploader" :action="actionUrl" :show-file-list="false"
                :on-success="handleAdverSuccess" :before-upload="beforeAdverUpload">
                <img v-if="form.adver_image" :src="form.adver_image" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="ICON图标" prop="icon">
              <div style="width: 30%;">
                <el-input v-model="form.icon"></el-input>
              </div>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="clickCancel">取 消</el-button>
            <el-button type="primary" v-if="dialogSubmit" @click="submitForm">确 定</el-button>
            <el-button type="primary" v-if="dialogEdit" @click="handleEdit">保 存</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </d2-container>
</template>

<script>
  import {
    imagesUploadUrl,
  } from '@/utils/interface'
  import {
    recordcategoryTreeUrl,
    recordcategoryListUrl,
    recordcategoryDetailUrl,
    recordcategoryCreateUrl,
    recordcategoryUpdateUrl,
    recordcategoryDeleteUrl
  } from '@/utils/socialize'
  import {
    baseURL
  } from '@/utils/request'
  export default {
    name: 'socializeCategory',
    data() {
      return {
        categoriesList: [],
        categoriesTree: [],
        defaultProps: {
          children: 'children',
          label: 'category_name'
        },
        dialogVisible: false,
        dialogSubmit: false,
        dialogEdit: false,
        form: {
          category_name: '',
          types: 0,
          cover_image: '',
          icon: '',
          parent: '',
        },
        props: {
          value: 'id',
          label: 'category_name',
        },
        rules: {
          category_name: [{
            required: true,
            message: '请输入分类名称',
            trigger: 'blur'
          }]
        },
        queryInfo: {
          page: 1,
          pageSize: 10
        },
        total: 1,
        actionUrl: baseURL + imagesUploadUrl,
        takeCategoriesId: ''
      }
    },
    created() {
      this.initData()
      this.handleSuccess = this.handleSuccess.bind(this);
    },
    methods: {
      initData() {
        this.getCategoriesList()
        this.getCategoriesTree()
      },
      getCategoriesList() {
        this.$get(recordcategoryListUrl, this.queryInfo).then(res => {
          this.categoriesList = res.data.data.list
          this.total = res.data.data.total
        })
      },
      getCategoriesTree() {
        this.$get(recordcategoryTreeUrl, this.queryInfo).then(res => {
          this.categoriesTree = res.data.data.list
        })
      },
      handleNodeClick(data) {
        console.log(data);
      },
      // 分页页码显示条数
      handleSizeChange(newSize) {
        // 把每页显示多少数据重新赋值
        this.queryInfo.pageSize = newSize
        this.getCategoriesList()
      },
      // 翻页事件
      handleCurrentChange(newPage) {
        this.queryInfo.page = newPage
        this.getCategoriesList()
      },
      addCategory() {
        this.dialogVisible = true
        this.dialogEdit = false
        this.dialogSubmit = true
      },
      clickCancel() {
        this.dialogVisible = false
        this.form = {}
        this.form.cover_image = ''
        this.form.adver_image = ''
      },
      handleCascaderChange(value) {
        // 将选中的值转换为字符串类型
        this.form.parent = value.join(',');
      },
      // 提交表单
      submitForm() {
        this.$refs.form.validate(valid => {
          if (valid) {
            this.$post(recordcategoryCreateUrl, this.form).then(res => {
              this.getCategoriesList()
              this.getCategoriesTree()
              this.dialogVisible = false
              this.$message.success('添加成功')
              this.form = {}
            })
          } else {
            return false
          }
        })
      },
      openDelete(catagoryId) {
        this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 在确定时执行handleDelete的删除
          this.handleDelete(catagoryId);
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      handleDelete(categoryId) {
        this.$del(recordcategoryDeleteUrl + categoryId + '/').then(res => {
          this.getCategoriesList()
          this.getCategoriesTree()
        })
      },
      handleSuccess(response, file, fileList) {
        this.form.cover_image = response.data.url
      },
      handleAdverSuccess(response, file, fileList) {
        this.form.adver_image = response.data.url
      },
      beforeAdverUpload() {

      },
      handleRemove(file) {
        this.$delete(imagesUploadUrl + `${file.response.data.id}/`).then(response => {}).catch(error => {
          console.error(error)
        })
      },
      handlePictureCardPreview(file) {
        this.dialogVisible = true;
      },
      handlePictureAdverdPreview(file) {
        this.dialogVisible = true;
      },
      categorEdit(categoriesId) {
        this.dialogVisible = true
        this.dialogEdit = true
        this.dialogSubmit = false
        this.takeCategoriesId = categoriesId
        this.$get(recordcategoryDetailUrl + categoriesId + '/').then(res => {
          this.form = {
            category_name: res.data.data.category_name,
            cover_image: res.data.data.cover_image,
            icon: res.data.data.icon,
            parent: res.data.data.parent,
          }
        })
      },
      handleChange(value) {
        if (value && value.length > 0) {
          this.form.parent = value[value.length - 1]; // 更新form.category的值为选中的最后一个值
        }
        console.log(this.form.parent);
      },
      handleEdit() {
        this.$put(recordcategoryUpdateUrl + this.takeCategoriesId + '/', this.form).then(res => {
          if (res.data.code == 200) {
            this.dialogVisible = false
            this.$message({
              type: 'success',
              message: '修改成功'
            });
            this.getCategoriesList()
            this.getCategoriesTree()
            this.form = {}

          }
        })
      }
    }
  }
</script>
<style lang="scss">
  .category-tree {
    width: 18%;

    .category-tree-title {
      height: 38px;
      min-height: 38px;
      background-color: #62A8D1;
    }
  }

  .el-tree-node__content {
    height: 42px;
  }
</style>